package m.jclecai.com.fragment;


import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.GroupBuyDetailActivity;
import m.jclecai.com.activity.MainActivity;
import m.jclecai.com.activity.WebHelperActivity;
import m.jclecai.com.adapter.GroupBuyAdapter;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.GroupBuyBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.dialog.GroupBuyScreenDialog;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.pop.MyLotteryMenuPopUpWindow;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.responseBody.GroupBuyBody;


/**
 * 合买页面
 */
public class GroupBuyFragment extends BaseFragment implements PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener {

    @BindView(R.id.rg_count)
    LinearLayout rgCount;
    @BindView(R.id.pr_listview)
    PullToRefreshListView prListview;
    GroupBuyAdapter adapter;
    @BindView(R.id.rb_one)
    RadioButton rbOne;
    @BindView(R.id.iv_one)
    ImageView ivOne;
    @BindView(R.id.rb_two)
    RadioButton rbTwo;
    @BindView(R.id.iv_two)
    ImageView ivTwo;
    @BindView(R.id.rb_three)
    RadioButton rbThree;
    @BindView(R.id.iv_three)
    ImageView ivThree;
    @BindView(R.id.rb_four)
    RadioButton rbFour;
    @BindView(R.id.iv_four)
    ImageView ivFour;

    private List<GroupBuyBean> lists;
    String type, desc;
    int page = 1;
    int tabIndex = 0;
    MyLotteryMenuPopUpWindow popUpWindow;
    String[] menus;
    //排序
    boolean sort = false;//false 降序 true升序

    String oflag="";
    String progress="";
    String loss="";

    @Override
    public int getLayoutId() {
        return R.layout.fragment_group_buy;
    }

    @Override
    public void initView() {
        super.initView();
        setTitle("全部合买", R.mipmap.arrow);
        rightOptionText("合买帮助");
        leftOptionText("筛选",-1);
        tvBack.setCompoundDrawables(null,null,null,null);
        lists = new ArrayList<>();
        adapter = new GroupBuyAdapter(getActivity(), lists);
        prListview.setAdapter(adapter);
        prListview.setOnRefreshListener(this);
        prListview.setOnItemClickListener(this);
        type = "";
        desc = "jindu";
        showLoadingLayout(prListview);
        //getData();
        showEmptyLayout();

        final MainActivity activity = (MainActivity) getActivity();

        new AlertDialog.Builder(getActivity())
                .setMessage("功能开发中...")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                activity.selectHomeTab();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                activity.selectHomeTab();
            }
        }).show();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            final MainActivity activity = (MainActivity) getActivity();

            new AlertDialog.Builder(getActivity())
                    .setMessage("功能开发中...")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            activity.selectHomeTab();
                        }
                    }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    activity.selectHomeTab();
                }
            }).show();
        }
    }

    @OnClick(R.id.tv_right_option)
    public void showClickRight(){
        //这里是加载右边合买帮助；
        String url="file:///android_asset/groupBuyHtml/" + "heima" + ".html";
        startActivity(WebHelperActivity.getInstance(getActivity(),url,false,"合买帮助"));
    }

    @OnClick(R.id.tv_back)
    public void onClickLeft(){
        GroupBuyScreenDialog groupBuyScreenDialog = new GroupBuyScreenDialog(getActivity(), new GroupBuyScreenDialog.OnDialogClickListener() {
            @Override
            public void onClick(boolean isSure, String secrecy, String progress, String baoDi) {
                if(isSure){
                    //这里我们是需要重新请求；
                    oflag=secrecy;
                    GroupBuyFragment.this.progress=progress;
                    GroupBuyFragment.this.loss=baoDi;
                    getData();
                }
            }
        },oflag,GroupBuyFragment.this.progress,GroupBuyFragment.this.loss);
        groupBuyScreenDialog.show();
    }

    @OnClick({R.id.tv_mid_title, R.id.iv_title_icon})
    void showGuideMenu() {
        menus = getResources().getStringArray(
                R.array.group_buy_menu);
        final String[] types = getResources().getStringArray(R.array.group_buy_menu_type);
        popUpWindow = new MyLotteryMenuPopUpWindow(getActivity(), menus, types, tabIndex, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                setTitle(menus[position]);
                type = types[position];
                lists.clear();
                adapter.notifyDataSetChanged();
                page = 1;
                if (position > 0)
                    desc = getCheckDesc();
                showLoadingLayout(prListview);
                getData();
                if (popUpWindow.isShowing()) {
                    popUpWindow.dismiss();
                }
                tabIndex = position;
                popUpWindow.notifyDataSetChanged();
            }
        }, new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                startAnimation(ivTitleIcon, R.anim.rotate_180_360);
            }
        });
        startAnimation(ivTitleIcon, R.anim.rotate_0_180);
        popUpWindow.setPager(tabIndex);
        popUpWindow.showAsDropDown(rlBar);
    }


    void getData() {
//        if(TextUtils.isEmpty(type))
//            desc = "id";
        Map<String, String> pair = new HashMap<>();
        pair.put("page", String.valueOf(page));
        pair.put("desc", desc);
        pair.put("type", type);

        pair.put("oflag", oflag);
        pair.put("progress", progress);
        pair.put("loss", loss);

        HttpManager.postAsyn(Constant_Url.GROUP_BUY, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
                if (prListview != null)
                    prListview.onRefreshComplete();
                showInternetOffLayout();
            }

            @Override
            public void onResponse(String response) {
                closeLoadingLayout();
                dissDialog();
                if (prListview != null)
                    prListview.onRefreshComplete();
                GroupBuyBody body = FastOk.get(response, GroupBuyBody.class);
                if (body != null && body.getRecords() != null && body.getRecords().size() > 0) {
                    page++;
                    if(lists != null)
                        lists.addAll(body.getRecords());
                }
                if (lists != null && lists.size() <= 0)
                    showEmptyLayout();
                adapter.notifyDataSetChanged();
            }
        }, pair);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        //下拉
        lists.clear();
        page = 1;
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        getData();
    }

    @OnClick({R.id.rb_one, R.id.rb_two, R.id.rb_three, R.id.rb_four})
    void selectDesc(View view) {
        lists.clear();
        adapter.notifyDataSetChanged();
        page = 1;
        String tag = view.getTag().toString();
        //如果desc不包含当前tag表明切换了按钮
        if (!desc.contains(tag)) {
            sort = false;
        } else {
            sort = !sort;
        }
        //降序升序
        if (sort) {
            desc = "a" + tag;
        } else {
            desc = tag;
        }
        resetRbStatus();
        showSorIcon(view);
        showLoadingLayout(prListview);
        getData();

    }

    //切换图标状态
    void showSorIcon(View view) {
        RadioButton rb = (RadioButton) view;
        rb.setChecked(true);
        if (rbOne.isChecked()) {
            ivOne.setImageResource(sort ? R.mipmap.coin_sort3 : R.mipmap.coin_sort2);
        } else if (rbTwo.isChecked()) {
            ivTwo.setImageResource(sort ? R.mipmap.coin_sort3 : R.mipmap.coin_sort2);
        } else if (rbThree.isChecked()) {
            ivThree.setImageResource(sort ? R.mipmap.coin_sort3 : R.mipmap.coin_sort2);
        } else if (rbFour.isChecked()) {
            ivFour.setImageResource(sort ? R.mipmap.coin_sort3 : R.mipmap.coin_sort2);
        }
    }

    //重置所有按钮状态
    void resetRbStatus() {
        rbOne.setChecked(false);
        ivOne.setImageResource(R.mipmap.coin_sort1);

        rbTwo.setChecked(false);
        ivTwo.setImageResource(R.mipmap.coin_sort1);

        rbThree.setChecked(false);
        ivThree.setImageResource(R.mipmap.coin_sort1);

        rbFour.setChecked(false);
        ivFour.setImageResource(R.mipmap.coin_sort1);
    }

    //由于全部合买desc为id与radiobutton上的desc不符
    // 所以在从合买切换后获取当前RadioButton选中的tag值
    String getCheckDesc() {
        if (rbOne.isChecked()) {
            desc = rbOne.getTag().toString();
        } else if (rbTwo.isChecked()) {
            desc = rbTwo.getTag().toString();
        } else if (rbThree.isChecked()) {
            desc = rbThree.getTag().toString();
        } else if (rbFour.isChecked()) {
            desc = rbFour.getTag().toString();
        }
        //降序升序
        if (sort) {
            desc = "a" + desc;
        }
        return desc;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
        checkLogin(new Callback() {
            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                startActivity(new Intent(getActivity(), GroupBuyDetailActivity.class)
                        .putExtra("bean", JSON.toJSONString(lists.get(position - 1))));
            }
        });
    }

    @Override
    public void OnRetry(String btnMessage) {
        showLoadingLayout(prListview);
        getData();
    }
}
